package com.cy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
/**
 * 当我们的主启动类时@EnableFeignClients注解描述时，spring工程
 * 在启动时会扫描@deignClient注解描述时接口
 */
@EnableFeignClients
public class ScaConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScaConsumerApplication.class, args);
    }

    /**
     * springboot工程中可以使用此对象调用第三方服务
     * @return
     */
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    @LoadBalanced
    public RestTemplate loadBalancedRestTemplate(){
        return new RestTemplate();
    }

    @RestController
    public class ConsumerController{

        @Value("${spring.application.name}")
        private String consumerName;
        @Autowired
        private RestTemplate restTemplate;
        @GetMapping("/consumer/doRestEcho1")
        public String doEcho(){
            //定义服务提供方的地址
            String url = "http://localhost:8081/provider/echo/"+consumerName;
            //调用服务提供方(sca-provider)
            return restTemplate.getForObject(url, String.class);
        }

        //LoadBalancerClient 此对象底层基于Ribbon实现负载均衡
        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @GetMapping("/consumer/doRestEcho2")
        public String doEcho2(){
            ServiceInstance choose = loadBalancerClient.choose("sca-provider");
            String host = choose.getHost();
            int port = choose.getPort();
            //定义服务提供方的地址
            String url = "http://"+host+":"+port+"/provider/echo/"+consumerName;
            //调用服务提供方(sca-provider)
            return restTemplate.getForObject(url, String.class);
        }

        @Autowired
        private RestTemplate loadBalancedRestTemplate;
        @GetMapping("/consumer/doRestEcho3")
        public String doEcho3(){
            //定义服务提供方的地址
            String url = String.format("http://%s/provider/echo/%s","sca-provider",consumerName);
            //调用服务提供方(sca-provider)
            return loadBalancedRestTemplate.getForObject(url, String.class);
        }


    }


}
